# -*- coding: utf-8 -*-
from Public_lib import *
import MySQLdb

#添加主机资源
class Modulehandle():
    def __init__(self,moduleid,hosts,sys_param_row):
        self.hosts = ""
        self.Runresult = ""
        self.moduleid = moduleid
        self.sys_param_array= sys_param_row
        self.hosts=target_host(hosts,"IP")

    def run(self):
        try:
            conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='OMServer',port=3306)
            cur=conn.cursor()
            cur.execute("select count(*) from server_fun_categ where server_categ_name='"+self.sys_param_array[0]+"'")
            abc = cur.fetchone()
            if abc==(0L,): #如果没有操作系统名称
                cur.execute("insert into server_fun_categ(server_categ_name) values('"+self.sys_param_array[0]+"')")
                cur.execute("insert into server_app_categ select ID,ID,server_categ_name from server_fun_categ where server_categ_name='"+self.sys_param_array[0]+"'")
                cur.execute("insert into server_list values('"+self.sys_param_array[0]+"','"+self.sys_param_array[1]+"','"+self.sys_param_array[1]+"','Linux',1)")
                cur.execute("update server_list set server_app_id=(select id from server_fun_categ where server_categ_name='"+self.sys_param_array[0]+"') where server_wip='"+self.sys_param_array[1]+"'")
                conn.commit()
            else:
                cur.execute("insert into server_list values('"+self.sys_param_array[0]+"','"+self.sys_param_array[1]+"','"+self.sys_param_array[1]+"','Linux',1)")
                cur.execute("update server_list set server_app_id=(select id from server_fun_categ where server_categ_name='"+self.sys_param_array[0]+"') where server_wip='"+self.sys_param_array[1]+"'")
                conn.commit()
            cur.close()
            conn.close()
            host=self.sys_param_array[1]+" ansible_ssh_user="+self.sys_param_array[2]+" ansible_ssh_pass="+self.sys_param_array[3]+"\n"
            with open('/etc/ansible/hosts','a') as f:
                f.write(host)
        except Exception,e:
            return str(e)
        self.Runresult = "添加成功\n操作系统:"+self.sys_param_array[0]+"\nIP:"+self.sys_param_array[1]+"\n用户名："+self.sys_param_array[2]+"\n密码："+self.sys_param_array[3]+"\n"
        return self.Runresult
